package com.cheyunkeji.er.utils.version;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.cheyun.netsalev3.R;

import java.io.File;


public class UpdateVersionUtils {

    // 获取当前包信息
    public static PackageInfo getPackageInfo(Context context) {
        PackageManager packageManager = context.getPackageManager();
        try {
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            return packageInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getVersionInfo(Context context) {
        return getPackageInfo(context).versionName;
    }

    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }


    public static long loadAPP(Context context, String url) {
        long id = 0;
        if (context != null && !TextUtils.isEmpty(url)) {
            DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            Uri parse = Uri.parse(url);
            DownloadManager.Request request = new DownloadManager.Request(parse)
                    .setTitle(context.getResources().getString(R.string.app_name))
                            // .setDescription("正在下载")
                            //    .setVisibleInDownloadsUi(true)
                            //    .setDestinationInExternalPublicDir("download", "update.apk")
                    .setMimeType("application/vnd.android.package-archive") // 设置下载类型
                    .setAllowedOverRoaming(true);// 所有网络能都下载
            String appinfo = "jingpai" + System.currentTimeMillis() + ".apk";
            if (isFolderExist(Environment.DIRECTORY_DOWNLOADS)) {
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, appinfo);
            } else {
                request.setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, appinfo);
            }
            id = downloadManager.enqueue(request);
            context.getSharedPreferences("config", Activity.MODE_PRIVATE).edit().putLong("load_id", id).commit();  // 写入让2个id 对应
            context.getSharedPreferences("config", Activity.MODE_PRIVATE).edit().putString("load_info", appinfo).commit();  // 写入让2个id 对应
            request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);
        }
        return id;
    }

    private static boolean isFolderExist(String dir) {
        File folder = Environment.getExternalStoragePublicDirectory(dir);
        return (folder.exists() && folder.isDirectory()) ? true : folder.mkdirs();
    }


    public static boolean isWifi(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI;
    }


    public static String getFilePathFromUri(Context c, Uri uri) {
        String filePath = null;
        if ("content".equals(uri.getScheme())) {
            String[] filePathColumn = {MediaStore.MediaColumns.DATA};
            ContentResolver contentResolver = c.getContentResolver();

            Cursor cursor = contentResolver.query(uri, filePathColumn, null,
                    null, null);

            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
        } else if ("file".equals(uri.getScheme())) {
            filePath = new File(uri.getPath()).getAbsolutePath();
        }
        // Log.i(TAG, "filePath="+filePath);
        return filePath;
    }

}
